<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="查询条件">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-select v-model="searchType" placeholder="选择查询类型" style="width: 100%">
              <el-option label="订单号" value="orderNumber"></el-option>
              <el-option label="用户昵称" value="userName"></el-option>
              <el-option label="用户ID" value="userId"></el-option>
              <el-option label="店铺名称" value="shopName"></el-option>
              <el-option label="店铺ID" value="shopId"></el-option>
            </el-select>
          </el-col>
          <el-col :span="16">
            <el-input 
              v-model="searchValue" 
              :placeholder="getSearchPlaceholder()" 
              clearable 
              @keyup.enter.native="handleQuery" 
              @clear="handleClearSearch"
            />
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="queryParams.paymentMethod" placeholder="请选择支付方式" clearable>
          <el-option v-for="dict in dict.type.payment_method" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" @change="handleDateChange"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-if="refreshTable" v-loading="loading" :data="orderList" border>
      <el-table-column label="订单号" prop="orderNumber" width="180" />
      <el-table-column label="用户昵称" align="center" width="120">
        <template slot-scope="scope">
          <div>{{ scope.row.userName || '未知用户' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="用户ID" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.userId || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户手机" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.userPhone || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" width="120">
        <template slot-scope="scope">
          <div>{{ scope.row.shopName || '未知商家' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="店铺ID" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.shopId || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" width="120">
        <template slot-scope="scope">
          <div>总计: ¥{{ scope.row.totalAmount }}</div>
          <div class="text-muted">商品: ¥{{ scope.row.productAmount }}</div>
          <div class="text-muted">配送: ¥{{ scope.row.deliveryFee }}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag 
            :type="getStatusTagType(scope.row.status)"
            size="small"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" width="100">
        <template slot-scope="scope">
          <el-tag 
            :type="getPaymentTagType(scope.row.paymentMethod)"
            size="small"
          >
            {{ getPaymentText(scope.row.paymentMethod) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') || '未支付' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
        
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detailOpen" width="1000px" append-to-body>
      <order-detail v-if="detailOpen" :order-id="detailOrderId" @close="detailOpen = false"></order-detail>
    </el-dialog>


  </div>
</template>

<script>
import { listOrder, getOrder } from "@/api/order/order";
import OrderDetail from "./detail";

export default {
  name: "Order",
  dicts: ['order_status', 'payment_method'],
  components: {
    OrderDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情订单ID
      detailOrderId: null,
      // 重新渲染表格状态
      refreshTable: true,
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],
      // 搜索类型
      searchType: 'orderNumber',
      // 搜索值
      searchValue: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        userName: null,
        userId: null,
        shopName: null,
        shopId: null,
        status: null,
        paymentMethod: null,
        beginTime: null,
        endTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = this.handleTreeData(response.rows);
        this.total = response.total;
        this.loading = false;
        console.log(response);

      });
    },
    /** 处理树形数据 */
    handleTreeData(data) {
      // 这里可以根据需要处理数据，比如按商家分组等
      return data;
    },
    /** 转换订单数据 */
    normalizeOrder(data) {
      return data;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 清空所有搜索参数
      this.queryParams.orderNumber = null;
      this.queryParams.userName = null;
      this.queryParams.userId = null;
      this.queryParams.shopName = null;
      this.queryParams.shopId = null;
      
      // 根据选择的搜索类型设置对应的查询参数
      if (this.searchValue && this.searchType) {
        this.queryParams[this.searchType] = this.searchValue;
      }
      
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.searchType = 'orderNumber';
      this.searchValue = '';
      this.resetForm("queryForm");
      this.queryParams.orderNumber = null;
      this.queryParams.userName = null;
      this.queryParams.userId = null;
      this.queryParams.shopName = null;
      this.queryParams.shopId = null;
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.handleQuery();
    },
    /** 日期范围改变 */
    handleDateChange(val) {
      if (val) {
        this.queryParams.beginTime = val[0];
        this.queryParams.endTime = val[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.detailOrderId = row.id;
      this.detailOpen = true;
    },
    /** 获取搜索框占位符 */
    getSearchPlaceholder() {
      const placeholders = {
        orderNumber: '请输入订单号',
        userName: '请输入用户昵称',
        userId: '请输入用户ID',
        shopName: '请输入店铺名称',
        shopId: '请输入店铺ID'
      };
      return placeholders[this.searchType] || '请输入查询内容';
    },
    /** 清空搜索框 */
    handleClearSearch() {
      this.searchValue = '';
      this.handleQuery();
    },

    /** 获取订单状态标签类型 */
    getStatusTagType(value) {
      const statusTypes = {
        '0': 'info',     // 待支付
        '1': 'warning',  // 已支付
        '2': 'primary',  // 制作中
        '3': 'success',  // 配送中
        '4': 'success',  // 已完成
        '5': 'danger'    // 已取消
      };
      return statusTypes[value] || 'default';
    },
    /** 获取支付方式标签类型 */
    getPaymentTagType(value) {
      const paymentTypes = {
        '1': 'success',  // 微信支付
        '2': 'primary',  // 支付宝
        '3': 'warning'   // 现金支付
      };
      return paymentTypes[value] || 'default';
    },
    /** 获取订单状态文本 */
    getStatusText(value) {
      const statusOption = this.dict.type.order_status?.find(item => item.value == value);
      return statusOption ? statusOption.label : '未知状态';
    },
    /** 获取支付方式文本 */
    getPaymentText(value) {
      const paymentOption = this.dict.type.payment_method?.find(item => item.value == value);
      return paymentOption ? paymentOption.label : '未知方式';
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        status: null,
        remark: null
      };
      this.resetForm("form");
    }
  }
};
</script>

<style scoped>
.text-muted {
  color: #999;
  font-size: 12px;
}
</style>
